package com.yzy.yzy_crm.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yzy.yzy_crm.entity.*;
import com.yzy.yzy_crm.mapper.*;
import com.yzy.yzy_crm.service.*;
import com.yzy.yzy_crm.utils.Md5Utils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class LoginController {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IUserService iUserService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private IUserRoleService userRoleService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IRoleDepartmentService roleDepartmentService;

    @Autowired
    private IPermissionService permissionService;

    @Autowired
    private IRolePermissionService rolePermissionService;

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private RoleDepartmentMapper roleDepartmentMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Autowired
    private CustomerMapper customerMapper;

    @Autowired
    private ContactMapper contactMapper;

    @Autowired
    private IBusinessService businessService;

    @Autowired
    private BOCMapper bocMapper;

    @Autowired
    private ICustomerService customerService;

    @Autowired
    private OrdersMapper ordersMapper;


    @RequestMapping("/doLogin")
    public Map doLogin(@RequestBody Map<String,String> map){
        System.out.println("==============");
        System.out.println(map);
        System.out.println("==============");
        Map<String,Object> result=new HashMap<>();
        UsernamePasswordToken token=new UsernamePasswordToken(map.get("username"),map.get("password"));
        Subject subject = SecurityUtils.getSubject();
        result.put("code","ok");
        try {
            subject.login(token);
            System.out.println("登录成功");
        }catch (UnknownAccountException e){
            e.printStackTrace();
            System.out.println("登录失败");
        }
        return result;
    }


    /*
    * 用户名
    * */


    /*
    * 分页查询
    * */
    @RequestMapping("/Select")
    public Map<String,Object> select(Integer page, Integer limit){
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<User> pa=userMapper.selectUserRole(p);
        System.out.println(pa);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        System.out.println(map);
        return map;
    }

    /*
     * 员工分页查询
     * */
    @RequestMapping("/SelectUserList")
    public Map<String,Object> selectUserList(Integer page, Integer limit){
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<User> pa=iUserService.page(p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/SelectDepartmentList")
    public Map<String,Object> SelectDepartmentList(Integer page, Integer limit){
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<User> pa=userMapper.selectDepartment(p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/selectPermissionList")
    public Map<String,Object> selectPermissionList(Integer page, Integer limit){
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<User> pa=userMapper.selectAllTbale(p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/SelectCustmoerList")
    public Map<String,Object> SelectCustmoerList(Integer page, Integer limit){
        Subject subject = SecurityUtils.getSubject();
        User user= (User) subject.getPrincipals().getPrimaryPrincipal();
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<User> pa=customerMapper.SelectCustmoer(user.getUserId(),p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/SelectContact")
    public Map<String,Object> SelectContact(Integer page, Integer limit){
        Subject subject = SecurityUtils.getSubject();
        User user= (User) subject.getPrincipals().getPrimaryPrincipal();
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
/*        Customer customer = customerMapper.SelectCustmoer(user.getUserId());
        System.out.println("客户ID："+customer.getCustomerId());*/
        IPage<User> pa=contactMapper.SelectContact(user.getUserId(),p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/SelectOrder")
    public Map<String,Object> SelectOrder(Integer page, Integer limit){
        Subject subject = SecurityUtils.getSubject();
        User user= (User) subject.getPrincipals().getPrimaryPrincipal();
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<User> pa=customerMapper.SelectOrder(user.getUserId(),1,p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/SelectAllCustmoer")
    public Map<String,Object> SelectAllCustmoer(Integer page, Integer limit){
        Subject subject = SecurityUtils.getSubject();
        User user= (User) subject.getPrincipals().getPrimaryPrincipal();
        Page<User> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<User> pa=customerMapper.SelectAllCustmoer(p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/SelectBusiness")
    public Map<String,Object> SelectBusiness(Integer page, Integer limit){
        Subject subject = SecurityUtils.getSubject();
        User user= (User) subject.getPrincipals().getPrimaryPrincipal();
        Page<Business> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        IPage<Business> pa=businessService.page(p);
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","查询情况");
        map.put("count",pa.getTotal());
        map.put("data",pa.getRecords());
        return map;
    }

    @RequestMapping("/SelectBOC")
    public Map<String,Object> SelectBOC(Integer page, Integer limit){
        Subject subject = SecurityUtils.getSubject();
        User user= (User) subject.getPrincipals().getPrimaryPrincipal();
        Page<BusinessOrdersCustomer> p=new Page<>();
        p.setCurrent(page);
        p.setSize(limit);
        List<Customer> customers = customerMapper.SelectOrder(user.getUserId(),1);
        Map<String,Object> map=new HashMap<>();
        for (Customer customer : customers) {
            System.out.println(customer.getCustomerId());
            IPage<BusinessOrdersCustomer> pa=bocMapper.SelectById(customer.getCustomerId(),p);
            map.put("code",0);
            map.put("msg","查询情况");
            map.put("count",pa.getTotal());
            map.put("data",pa.getRecords());
            System.out.println(map);
        }
        return map;
    }

    @RequestMapping("/SelectCount")
    public Map<String,Object> SelectCount(Integer page, Integer limit){
        Map<String,Object> map=new HashMap<>();
        map.put("user",userMapper.selectcount());
        map.put("customer",customerMapper.selectcount());
        map.put("orders",ordersMapper.selectcount());
        return map;
    }


    @RequestMapping("/SelectRole")
    public Map<String,Object> SelectRole(){
        List<Role> list = roleService.list();
        Map<String,Object> map=new HashMap<>();
        map.put("data",list);
        return map;
    }

    /*
     *查询部门
     * */
    @RequestMapping("/SelectDepartment")
    public Map<String,Object> SelectDepartment(){
        List<Department> list = departmentService.list();
        Map<String,Object> map=new HashMap<>();
        map.put("data",list);
        return map;
    }

    /*
    *查询权限
    * */
    @RequestMapping("/SelectPermission")
    public Map<String,Object> SelectPermission(){
        List<Permission> list = permissionService.list();
        Map<String,Object> map=new HashMap<>();
        map.put("data",list);
        return map;
    }

    /*
     * 删除
     * */
    @RequestMapping("/Delete")
    public boolean select(int userId){
        System.out.println(userId);
        roleDepartmentMapper.DeleteById(userId);//删除部门依赖
        rolePermissionMapper.DeleteById(userId);//删除权限依赖
        userRoleMapper.deleteByUserRoleId(userId);//删除角色依赖
        boolean b = iUserService.removeById(userId);//删除用户数据
        return b;
    }

    @RequestMapping("/UpdateRole")
    public boolean UpdateRole(@RequestBody Map<String,String> map){
        System.out.println(map);
        System.out.println(map.get("userId"));
        System.out.println(map.get("city"));
        int userId= Integer.parseInt(map.get("userId"));
        Role role = roleMapper.selectRoleByName(map.get("city"));
        System.out.println(role.getRoleId());
        boolean b = userRoleMapper.UpdateByUserRoleId(role.getRoleId(), userId);
        return b;
    }

    @RequestMapping("/UpdateDepartment")
    public boolean UpdateDepartment(@RequestBody Map<String,String> map){
        System.out.println(map);
        System.out.println(map.get("userId"));
        System.out.println(map.get("city"));
        int userId= Integer.parseInt(map.get("userId"));
        Department department = departmentMapper.SelectDepartment(map.get("city"));
        System.out.println(department.getDepartmentId());
        boolean b = departmentMapper.Update(department.getDepartmentId(), userId);
        return b;
    }

    @RequestMapping("/Update")
    public boolean update(@RequestBody Map<String,String> map){
        System.out.println(map);
        int userId=Integer.parseInt(map.get("userId"));
        int old=Integer.parseInt(map.get("old"));
        User user = new User(userId,map.get("userName"),null,null,map.get("name"),old,map.get("sex"),null);
        boolean b = iUserService.updateById(user);
        return b;
    }

    @RequestMapping("/Insert")
    public boolean insert(@RequestBody Map<String,String> map){
        System.out.println(map);
        String salt = Md5Utils.randomSalt();
        String password = Md5Utils.encryptPassword((String) map.get("password"), salt);
        String city = map.get("city");
        int old = Integer.parseInt(map.get("old"));
        User user=new User(null,map.get("userName"),password,salt,map.get("name"),old,map.get("sex"),null);
        Role role = roleMapper.selectRoleByName(city);/*根据角色名拿到角色信息获得ID*/
        Department department = departmentMapper.SelectDepartment(map.get("city2"));//根据部门名字查找到部门信息获得ID
        Permission permission = permissionMapper.SelectPermission(map.get("city3"));//根据权限名字查找到权限信息获得ID
        boolean save = iUserService.save(user);/*用户信息添加*/
        System.out.println(department);
        System.out.println(permission);
        System.out.println(map.get("city2"));
        System.out.println(map.get("city3"));
        System.out.println(department.getDepartmentId());
        System.out.println(permission.getPermissionId());
        System.out.println("自增ID"+user.getUserId());//自增ID
        System.out.println("权限ID"+role.getRoleId());//角色ID
        roleDepartmentService.save(new RoleDepartment(user.getUserId(),department.getDepartmentId()));/*添加到角色部门依赖表*/
        rolePermissionService.save(new RolePermission(user.getUserId(),permission.getPermissionId()));/*添加到角色权限依赖表*/
        userRoleService.save(new UserRole(user.getUserId(),role.getRoleId()));/*添加用户角色依赖*/
        return save;
    }
}
